<?php
namespace app\api\controller;

use app\api\controller\BaseController;
use app\api\validate\Permission as ValidatePermission;
use app\common\exception\ForbiddenException;
use app\common\exception\SuccessException;
use app\models\Permission as ModelsPermission;
// use Surest\Traits\TreeNode;

/**
 * 权限管理
 * Class Permission
 * @package app\admin\controller
 */
class Permission extends BaseController
{

    /**
     * 权限管理
     * 
     * @url api/v1/permission/index
     * @throws \app\common\exception\SuccessException
     */
    public function index()
    {
        $permissions = ModelsPermission::where(0, 0)
            ->order('method', 'desc')
            ->select()->toArray();
            echo ModelsPermission::getLastSql();die;
        $permissions = self::recursive_make_tree($permissions);

        throw new SuccessException(['content' => $permissions]);
    }

    /**
     * 初始化权限节点
     * 
     * @url api/v1/permission/init
     * @throws \app\common\exception\SuccessException
     */
    public function init_permission()
    {
        $r = ModelsPermission::init_((bool) request()->param('is_delete', 0));

        throw new SuccessException(['content' => $r]);
    }

    /**
     * 获取所有的权限
     */
    public function all(ModelsPermission $model)
    {
        $permissions = $model->field(['id', 'p_id', 'name'])->select()->toArray();

        $permissions = self::recursive_make_tree($permissions);
        throw new SuccessException(['content' => $permissions]);
    }

    /**
     * 获取权限信息
     * @param $id
     */
    public function read($id, ModelsPermission $model)
    {
        $permission = $model->find($id);

        throw new SuccessException(['content' => $permission]);
    }

    /**
     * 创建权限节点
     */
    public function save(ModelsPermission $models,  ValidatePermission $validate)
    {
        $data = $validate->goCheck();

        $models->create($data);
        
        throw new SuccessException(['msg' => '创建成功']);
    }

    /**
     * 更新权限
     * @param $id
     */
    public function update($id, ModelsPermission $models,  ValidatePermission $validate)
    {
        $data = $validate->goCheck();

        if(!$models->find($id)) {
            throw new ForbiddenException(['msg' => '权限不存在']);
        }

        $models->update($data, ['id' => $id]);
        
        throw new SuccessException(['msg' => '更新成功']);
    }

    /**
     * 删除权限
     * @param $id
     */
    public function delete($id, ModelsPermission $models,  ValidatePermission $validate)
    {
        if($models->destroy($id)){
            $models->where('p_id', $id)->delete();
        }
        throw new SuccessException(['msg' => '删除成功']);
    }
}